package com.pcbly.web.persistence.system;

/**
 * @author carl.song
 * Copyright (c) 2010 Lightsoft, International.
 * All rights reserved.
 *
 */
import java.util.List;

import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.bean.system.ProvinceCityBean;
import com.pcbly.web.persistence.HibernateBaseDao;
import com.pcbly.web.components.hibernate.support.Page;

@SuppressWarnings("unchecked")
public class ProvinceCityHibernateDao extends
		HibernateBaseDao<ProvinceCityBean> implements ProvinceCityDao {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5014355327125098162L;

	protected Class<ProvinceCityBean> getEntityClass() {
		return ProvinceCityBean.class;
	}

	public ProvinceCityHibernateDao() {
		super();
	}

	@Override
	public void saveProvinceCityBean(ProvinceCityBean system) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug(system.getId());
		}
		String id = (new GUID()).toString();
		system.setId(id);
		getHibernateTemplate().save(system);
	}

	@Override
	public void removeProvinceCityBeanByIds(String ids) throws Exception {
		// TODO Auto-generated method stub
		ids = ids.replaceAll(",", "','");
		String hsql = "delete from sys_province_city where ID in( '" + ids
				+ "')";
		getSession().createSQLQuery(hsql).executeUpdate();

	}

	public Page<ProvinceCityBean> findProvinceCityBeanByCond(
			ProvinceCityBean bean, Page<ProvinceCityBean> page,
			String orderByName, boolean asc) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("select * from sys_province_city where RECYCLED=0 ");
		if (!(bean == null)) {
		}
		if (asc) {
			// criteria.addOrder(Order.asc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" ");
		} else {
			// criteria.addOrder(Order.desc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" desc ");
		}
		Object obj = getSession().createSQLQuery(
				"select count(t.ID) from (" + sb + ")t").uniqueResult();
		if (obj == null) {
			obj = "0";
		}

		page.setTotalCount(Integer.parseInt(String.valueOf(obj)));
		if (page.getTotalCount() > 0) {
			int first = page.getFirst();
			int lpage = first + page.getPageSize();
			if (lpage > page.getTotalCount()) {
				lpage = page.getTotalCount();
			}
			List<ProvinceCityBean> beans = getSession().createSQLQuery(
					sb.toString()).addEntity(ProvinceCityBean.class).list()
					.subList(first, lpage);
			page.setResult(beans);
		}
		return page;
	}

	@Override
	public List<ProvinceCityBean> findProvinceCityBeansByParentId(
			String parentId) throws Exception {
		// TODO Auto-generated method stub

		String hsql = "from ProvinceCityBean  where parentId=? and recycled='0' order by orderBy ";
		return getSession().createQuery(hsql).setString(0, parentId).list();
	}
}